<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
              <a-input v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
              <select-user-by-dep
                placeholder="请选择申请人"
                v-model="model.proposer" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
              <j-select-depart placeholder="请选择申请部门" v-model="model.departId" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider>作废信息</a-divider>
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBillId">
                  <SelectPurchaseCalibrationInput :disabled="formDisabled" v-model="model.purchaseBillId" placeholder="请选择定标结果确认表单" @back="purchaseInfoBack"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="showdetailDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationProposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.invalidationProposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationDepartId">
                  <j-select-depart placeholder="请选择申请部门"  v-model="model.invalidationDepartId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationCreateTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.invalidationCreateTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="工期(供货期)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplyTime">
                  <j-date
                    :disabled="showdetailDisabled"
                    placeholder="请选择工期"
                    v-model="model.supplyTime"
                    date-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="开标时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="calibrationTime">
                  <j-date
                    date-format="YYYY-MM-DD HH:mm"
                    :disabled="showdetailDisabled"
                    placeholder="请选择开标时间"
                    :show-time="true"
                    v-model="model.calibrationTime"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="预算价（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="budget">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.budget"
                    placeholder="请输入预算价"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="开票方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceManner">
                  <a-input :disabled="showdetailDisabled" v-model="model.invoiceManner" placeholder="请输入开票方式" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input :disabled="showdetailDisabled" placeholder="请选择所属团队" v-model="model.teamId" :tdlx="3" @back="teamBack"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2">
            <div slot="header">
              <span>招标采购申请信息</span>
              <span style="color: red; font-size: 12px;">必须关联同一个项目的招标采购申请单</span>
            </div>
            <a-row :gutter="48">
              <ErpPurchaseCalibrationDetailList ref="calibrationDetailList" :disabled="showdetailDisabled" :teamId="model.teamId" @onBudget="onBudget"></ErpPurchaseCalibrationDetailList>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="中标信息">
            <a-row :gutter="48">
              <ErpPurchaseCalibrationUnitList ref="calibrationUnitList" :disabled="showdetailDisabled"></ErpPurchaseCalibrationUnitList>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="各厂家报价、谈判情况描述及选定该厂家供货的原因：（重点描述品牌、价格对比情况、原厂还是代理商等）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="quoteDescription">
                  <a-textarea :disabled="showdetailDisabled"
                              :max-length="500"
                              v-model="model.quoteDescription"
                              rows="10"
                              maxlength="5000"
                              placeholder="重点描述品牌、价格对比情况、是原厂还是代理商等"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="历史采购情况说明：  （重点描述品牌、价格情况）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="historyDescription">
                  <a-textarea
                    :disabled="showdetailDisabled"
                    :max-length="500"
                    v-model="model.historyDescription"
                    rows="10"
                    maxlength="1000"
                    placeholder="重点描述品牌、价格情况"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="与采购申请的差异：  （重点描述规格型号、参数及品牌、数量等更改项目）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="differenceDescription">
                  <a-textarea
                    :disabled="showdetailDisabled"
                    :max-length="500"
                    v-model="model.differenceDescription"
                    rows="10"
                    maxlength="1000"
                    placeholder="重点描述规格型号、参数及品牌、数量等更改项目"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="申购单位意见：  （对产品品牌、价格、数量的认可及增减等描述）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="opinionDescription">
                  <a-textarea
                    :disabled="showdetailDisabled"
                    :max-length="500"
                    v-model="model.opinionDescription"
                    rows="10"
                    maxlength="1000"
                    placeholder="对产品品牌、价格、数量的认可及增减等描述"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="showdetailDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="附件信息（1、询比价对比表；2、中标厂家盖章报价单；3、其它）">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!showdetailDisabled" :disabled="showdetailDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-row :gutter="48">
          <a-col :span="24">
            <a-form-model-item label="作废理由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationReason">
              <a-textarea :max-length="500" :disabled="formDisabled" v-model="model.invalidationReason" rows="4" placeholder="请输入作废理由"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48" v-if="formBpm">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" @click="onPrint">打印</a-button>
      </a-col>
    </a-row>
    <ErpPurchaseCalibrationFormPrint v-if="formBpm" class="print_style" id="calibrationContent" :formData="model" :formDataHistory="formData"></ErpPurchaseCalibrationFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import ErpPurchaseCalibrationDetailList from './reference/ErpPurchaseCalibrationDetailList'
import ErpPurchaseCalibrationUnitList from './reference/ErpPurchaseCalibrationUnitList'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpPurchaseCalibrationFormPrint from './ErpPurchaseCalibrationFormPrint' // 打印
import SelectPurchaseCalibrationInput from './SelectPurchaseCalibrationInput'
export default {
    name: 'ErpPurchaseCalibrationForm',
    components: {
      SelectTeamInput,
      ViewFileModal,
      SelectUserByDep,
      ErpPurchaseCalibrationDetailList,
      ErpPurchaseCalibrationUnitList,
      CommonFlowList,
      ErpPurchaseCalibrationFormPrint,
      SelectPurchaseCalibrationInput
    },
    mixins: [viewFile],
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        activeKey: ['1', '2', '3', '4'],
        model: {
          purchaseBill: null,
          purchaseBillId: null,
          invalidationReason: '',
          detailList: [],
          unitList: []
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          purchaseBillId: [
            { required: true, message: '请选择单据名称!', trigger: 'change' }
          ],
          invalidationReason: [
            { required: true, message: '请输入作废理由!', trigger: 'blur' },
          ],
        },
        url: {
          add: '/api/erp/purchase/procurement/erpPurchaseCalibration/add',
          edit: '/api/erp/purchase/procurement/erpPurchaseCalibration/edit',
          queryById: '/api/erp/purchase/procurement/erpPurchaseCalibration/queryById',
          gainBillNo: "/api/erp/purchase/procurement/erpPurchaseCalibration/gainBillNo",
          queryVerification: '/api/erp/purchase/procurement/erpPurchaseCalibration/referencedVerification',
          queryVerificationCancelling: '/api/erp/purchase/procurement/erpPurchaseCalibration/referencedVerificationCancelling',
        },
        teamIdBackups: null,
        userName: '',
        purchaseBillIdBackups: null,
        editCount: 0,
        showdetailDisabled:true
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      purchaseInfoBack(item){
        const that = this
        //判断不为空
        if(!!this.model.purchaseBillId && item.length > 0){
          //判断公司是否变化
          if(this.purchaseBillIdBackups !== item[0].id) {
            getAction(this.url.queryVerification,{ id: item[0].id}).then(res => {
              if(res.result == "校验通过"){
                getAction(this.url.queryVerificationCancelling,{ id: item[0].id}).then(response => {
                  if(response.result == "校验通过"){
                    //确认后进行改变
                    that.purchaseBillIdBackups = item[0].id
                    that.handleModelData(item[0])
                    that.model.purchaseBillId = item[0].id
                  } else {
                    that.$message.warning(response.message)
                    that.model.purchaseBillId = that.purchaseBillIdBackups
                  }
                })
              } else {
                that.$message.warning(res.message)
                that.model.purchaseBillId = that.purchaseBillIdBackups
              }
            })
          }
        }
      },
      handleModelData(val){
        // 选择单据 处理原表单数据
        this.$set(this.model,'invalidationPurchaseBill',val.purchaseBill)
        this.$set(this.model,'invalidationProposer',val.proposer)
        this.$set(this.model,'invalidationDepartId',val.departId)
        this.$set(this.model,'invalidationCreateTime',val.createTime)
        this.$set(this.model,'bpmBizTitle','作废-'+ this.userName + '-' + this.model.purchaseBill)
        this.$set(this.model,'supplyTime',val.supplyTime)
        this.$set(this.model,'calibrationTime',val.calibrationTime)
        this.$set(this.model,'budget',val.budget)
        this.$set(this.model,'invoiceManner',val.invoiceManner)
        this.$set(this.model,'teamId',val.teamId)
        this.$set(this.model,'quoteDescription',val.quoteDescription)
        this.$set(this.model,'historyDescription',val.historyDescription)
        this.$set(this.model,'differenceDescription',val.differenceDescription)
        this.$set(this.model,'opinionDescription',val.opinionDescription)
        this.$set(this.model,'remark',val.remark)
        this.$set(this.model,'purchaseFile',val.purchaseFile)
        this.teamIdBackups = this.model.teamId
        this.$refs.calibrationUnitList.loadData(1, this.model.id)
        this.$refs.calibrationDetailList.loadData(1, this.model.id)
      },
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo,{ type: '2' }).then((res)=>{
          if(res.success){
            that.model.purchaseBill = res.result//单据编号
            // that.model.bpmBizTitle = that.userName + '-' + that.model.purchaseBill//标题
          }
        })
      },
      add () {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({},{ 
          purchaseBill: '',
          purchaseBillId: '',
          invalidationReason: ''
        })
        this.$refs.calibrationUnitList.dataSource = []
        this.$refs.calibrationDetailList.dataSource = []
        this.$refs.calibrationDetailList.showAdd = false
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.proposer = this.userInfo().empId; // 当前登录人
        this.model.departId = this.userInfo().deptId; //当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.getBillNo() //获取单据编号
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        this.editCount = 0
        this.visible = true;
        if (this.model.id) {
          this.teamIdBackups = this.model.teamId
          this.$refs.calibrationUnitList.loadData(1, this.model.id)
          this.$refs.calibrationDetailList.loadData(1, this.model.id)
          // 升级版迭代1判断是否有项目id，有则显示新增按钮，没有则隐藏新增按钮
          // this.$refs.calibrationDetailList.showAdd = true // 显示隐藏新增按钮
        } else {
          this.$refs.calibrationUnitList.dataSource = []
          this.$refs.calibrationDetailList.dataSource = []
          this.$refs.calibrationDetailList.showAdd = false
        }
      },
      teamBack(item) {
        //判断不为空
        if(!!this.model.teamId && item.length > 0) {
          //判断团队是否变化
          if(this.teamIdBackups !== item[0].id) {
            let detailList = this.$refs.calibrationDetailList.submitForm()
            if(detailList.length > 0) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换所属团队，此操作将会清空招标采购申请信息明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.teamIdBackups = that.model.teamId
                  //清空子表数据
                  that.$refs.calibrationDetailList.dataSource = []
                  that.$refs.calibrationDetailList.showAdd = false
                },
                onCancel() {
                  that.model.teamId = that.teamIdBackups
                }
              });
            } else {
              this.teamIdBackups = item[0].id
            }
          }
        }
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      // 获取预算价
      onBudget (value) {
        if(this.editCount==0){
          this.editCount = 1
        } else {
          this.$set(this.model, 'budget', value)
        }
      },

      submitForm(type) {
        const that = this;
        // if (type == 'draft') {
        //   // 代表保存草稿不做校验
        //   this.submit(type)
        // } else if (type == 'submit') {
        //   let detailList = this.$refs.calibrationDetailList.submitForm()
        //   let unitList = this.$refs.calibrationUnitList.submitForm()
        //   if (!detailList.length > 0) {
        //     this.$message.warning('请添加招标采购申请信息！');
        //     this.$emit('unButtonDisable');
        //     return
        //   }
        //   if (!unitList.length > 0) {
        //     this.$message.warning('请添加中标信息！');
        //     this.$emit('unButtonDisable');
        //     return
        //   }
        //   // 触发表单验证
        //   this.$refs.form.validate(valid => {
        //     if (valid) {
        //       that.submit(type)
        //     } else {
        //       that.$emit('unButtonDisable')
        //     }
        //   })
        // } else {
        //   console.log('传参数，保存：draft，提交：submit')
        // }
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      },
      submit (type) {
        const that = this;
        let detailList = this.$refs.calibrationDetailList.submitForm() || []
        let unitList = this.$refs.calibrationUnitList.submitForm() || []
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.detailList = detailList
        this.model.unitList = unitList
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#calibrationContent',
          popTitle: '定标结果确认详情 · 禾美环保',
          endCallback() {

          }
        })
      }
      // backUserInfo(data) {
      //   this.model.applicant = data[0].orgDepart;//申请人单位
      //   this.model.departId = data[0].departmentId;//申请人部门
      // }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>